package com.zhang;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan(basePackageClasses = MybatisConfig.class)
@MapperScan("com.zhang.mapper")//用来扫描mapper.xml文件，将mapper.xml加入到spring中进行托管
@EnableTransactionManagement
public class MybatisConfig {


    @Bean
    public DataSource dataSource(){
        DruidDataSource druid = new DruidDataSource();
        druid.setDriverClassName("com.mysql.jdbc.Driver");
        druid.setUrl("jdbc:mysql://localhost:3306/crmsm?useSSl=false&characterEncoding=utf8&useUnicode=false&allowMultiQueries=true");
        druid.setUsername("root");
        druid.setPassword("123456");
        return druid;
    }

    @Bean
    public SqlSessionFactoryBean factoryBean(){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        return factoryBean;
    }


    @Bean
    public TransactionManager transactionManager(){
        DataSourceTransactionManager man = new DataSourceTransactionManager();
        man.setDataSource(dataSource());
        return man;
    }
}
